#include "widget_funca_smart_chat.h"
#include "ui_widget_funca_smart_chat.h"

Widget_funcA_Smart_chat::Widget_funcA_Smart_chat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcA_Smart_chat)
{
    ui->setupUi(this);
     manager = new QNetworkAccessManager(this);

}

Widget_funcA_Smart_chat::~Widget_funcA_Smart_chat()
{
    delete ui;
}

void Widget_funcA_Smart_chat::generate(const QString &prompt)
{
    QUrl url("http://127.0.0.1:11434/api/generate");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject body;
    body["model"] = "deepseek-r1:1.5b";
    body["prompt"] = prompt;
    body["stream"] = true; // 启用流式传输
    body["max_tokens"] = 512;

    QByteArray data = QJsonDocument(body).toJson();
    QNetworkReply *reply = manager->post(request, data);
    ui->textEdit_output->setText(ui->textEdit_output->toPlainText() +  "\nDeepSeek : ");
    connect(reply, &QNetworkReply::readyRead, this, [=]() {
        while (reply->canReadLine()) {
            QByteArray chunk = reply->readLine();
            QJsonDocument doc = QJsonDocument::fromJson(chunk);
            if (!doc.isNull() && doc.object().contains("response")) {
                QString result = doc.object()["response"].toString();
                qDebug() << "Chunk received:" << result;
                // 写入到界面
                ui->textEdit_output->setText(ui->textEdit_output->toPlainText() +  result);
            }
        }
    });
    ui->textEdit_output->setText(ui->textEdit_output->toPlainText() + "\n");

    connect(reply, &QNetworkReply::finished, this, [=]() {
        reply->deleteLater();
    });
}

void Widget_funcA_Smart_chat::handleResponse(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Error:" << reply->errorString();
        return;
    }

    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);
    QJsonObject json = doc.object();

    if (json.contains("response")) {
        QString result = json["response"].toString();
        qDebug() << "Response:" << result;
    }
}

void Widget_funcA_Smart_chat::on_Button_send_clicked()
{
    // 获取问题
    QString text_send = ui->textEdit_input->toPlainText();

    // 清空对话框
    ui->textEdit_input->clear();

    // 将问题写入到界面

    // ui->textEdit_output->setFont(QFont());
    ui->textEdit_output->setText(ui->textEdit_output->toPlainText() + "\n林靥 : ");
    ui->textEdit_output->setText(ui->textEdit_output->toPlainText() + text_send);
    ui->textEdit_output->setText(ui->textEdit_output->toPlainText() + "\n");

    // 发送问题
    this->generate(text_send);
}
